<?php 

class NewsModel extends BaseModel
{
	private $table;
	private $table_emails;
	
	/**
	 * Hold an instance of the class
	 * @var CommonPageModel
	 */
	private static $_instance = null;
	
	/**
	 * A private constructor
	 * Prevents direct creation of object
	 */
	private function __construct()
	{
		$this->_init();
		$this->table = TABLE_PREFIX . "news";
		$this->table_emails = TABLE_PREFIX . "news_emails";
	}

	/**
	 * The singleton method
	 * @return CommonPageModel
	 */
	public static function getInstance()
	{
		if (!self::$_instance instanceof self)
			self::$_instance = new self;

		return self::$_instance;
	}
	
	public function saveNews($args){

		if(!is_numeric($args["id_news"])) dibi::query("INSERT INTO ".$this->table." ", $args);
		else dibi::query("UPDATE ".$this->table." SET", $args, "WHERE id_news = %i", $args["id_news"]);
	}
	
	public function getNews($cond = array()){
		$order = array(
        'date' => 'desc'
		);
		
		$news = dibi::query("SELECT * FROM ".$this->table." WHERE %and", $cond ,"ORDER BY %by", $order)->fetchAll();
		
		return $news;
	}
	
	public function getDataSource($cond = array()){
		
		$order = array(
        'date' => 'desc'
		);
		
		return dibi::dataSource("SELECT * FROM ".$this->table." WHERE %and", $cond, " ORDER BY %by", $order);
	}
	
	public function getNewById($id_news){
		return dibi::query("SELECT * FROM ".$this->table." WHERE id_news = %i", $id_news)->fetch();
	}
	
	public function deleteNews($id_news){

		dibi::query("DELETE FROM ".$this->table." WHERE id_news = %i", $id_news);

	}
	
	public function getNewByName($name){
		return dibi::fetch("SELECT * FROM {$this->table} WHERE seo_title = %s", $name);
	}
	
	public function getPicture($id_file){
		return dibi::fetch("SELECT * FROM " . TABLE_FILES . " WHERE id_file = %i", $id_file);
	}
	
	public function emailExists($email){
		$email = dibi::select("email")
					->from($this->table_emails)
					->where("email = %s", $email)
					->fetchSingle();
					
		return empty($email) ? false : true;
		
	}
	
	public function emailAdd($email){
		
		$hash = sha1($email . 'salt');
		
		return dibi::insert($this->table_emails, array("email" => $email, "active" => 1, "hash" => $hash))->execute();
	}
	
	public function getEmails(){
		
		return dibi::select("*")
				->from($this->table_emails)
				->where("active = %i", 1)
				->fetchAll();
	}
	
	public function odhlasitNewsletter($hash){
		
		return dibi::delete($this->table_emails)
					->where("hash = %s", $hash)
					->execute();
	}
	
}

?>